#include <lib/std.mi>

Function string tokenizeSongInfo(String tkn, String sinfo);
Function getSonginfo(String SongInfoString);

Global Group frameGroup;
Global GuiObject mono, stereo;
Global Text bitrateText, FrequencyText;
Global Timer songInfoTimer;
Global String SongInfoString;

System.onScriptLoaded(){
	frameGroup = getScriptGroup();

	bitrateText = frameGroup.findObject("Bitrate");
	frequencyText = frameGroup.findObject("Frequency");

	mono = frameGroup.findObject("mono");
	stereo = frameGroup.findObject("stereo");

	songInfoTimer = new Timer;
	songInfoTimer.setDelay(1000);

	mono.hide();
	stereo.hide();

	if (getStatus() == STATUS_PLAYING) {
		String sit = getSongInfoText();
		if (sit != "") getSonginfo(sit);
		else songInfoTimer.setDelay(50); // goes to 1000 once info is available
		songInfoTimer.start();
	} else if (getStatus() == STATUS_PAUSED) {
		getSonginfo(getSongInfoText());
	}
}

System.onScriptUnloading(){
	delete songInfoTimer;
}

System.onPlay(){
	String sit = getSongInfoText();
	if (sit != "") getSonginfo(sit);
	else songInfoTimer.setDelay(50); // goes to 1000 once info is available
	songInfoTimer.start();
}

System.onStop(){
	songInfoTimer.stop();
	frequencyText.setText("(__)");
	bitrateText.setText("(___)");
	mono.hide();
	stereo.hide();
}

System.onResume(){
	String sit = getSongInfoText();
	if (sit != "") getSonginfo(sit);
	else songInfoTimer.setDelay(50); // goes to 1000 once info is available
	songInfoTimer.start();
}

System.onPause(){
	songInfoTimer.stop();
}

songInfoTimer.onTimer(){
	String sit = getSongInfoText();
	if (sit == "") return;
	songInfoTimer.setDelay(1000);
	getSonginfo(sit);
}

String tokenizeSongInfo(String tkn, String sinfo){
	int searchResult;
	String rtn;
	if (tkn=="Bitrate"){
		for (int i = 0; i < 5; i++) {
			rtn = getToken(sinfo, " ", i);
			searchResult = strsearch(rtn, "kbps");
			if (searchResult>0) return StrMid(rtn, 0, searchResult);
		}
		return "";
	}

	if (tkn=="Channels"){
		for (int i = 0; i < 5; i++) {
			rtn = getToken(sinfo, " ", i);
			searchResult = strsearch(rtn, "tereo");
			if (searchResult>0) return "stereo";
			searchResult = strsearch(rtn, "ono");
			if (searchResult>0) return "mono";
		}
		return "";
	}

	if (tkn=="Frequency"){
		for (int i = 0; i < 5; i++) {
			rtn = getToken(sinfo, " ", i);
			searchResult = strsearch(strlower(rtn), "khz");
			if (searchResult>0) {
				String r = StrMid(rtn, 0, searchResult);
				int dot = StrSearch(r, ".");
				if (dot != -1) return StrMid(r, 0, dot);
				return r;
			}

		}
		return "";
	}
	else return "";
}

getSonginfo(String SongInfoString) {
	String tkn;

	tkn = tokenizeSongInfo("Bitrate", SongInfoString);
	if(tkn != "") {bitrateText.setText("["+tkn+"]");}

	tkn = tokenizeSongInfo("Channels", SongInfoString);
	if(tkn == "stereo")  {
		stereo.show();
		mono.hide();
	} else {
		mono.show();
		stereo.hide();
	}

	tkn = tokenizeSongInfo("Frequency", SongInfoString);
	if(tkn != "") {frequencyText.setText("["+tkn+"]");}
}